package com.foodorder.controller;

import com.foodorder.dto.ApiResponse;
import com.foodorder.entity.Category;
import com.foodorder.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 分类控制器
 */
@RestController
@RequestMapping("/categories")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class CategoryController {
    
    private final CategoryService categoryService;
    
    /**
     * 根据店铺ID获取分类列表
     */
    @GetMapping("/store/{storeId}")
    public ApiResponse<List<Category>> getCategoriesByStore(@PathVariable Long storeId) {
        List<Category> categories = categoryService.findByStoreId(storeId);
        return ApiResponse.success(categories);
    }
    
    /**
     * 管理端分页查询分类
     */
    @GetMapping("/admin")
    public ApiResponse<Map<String, Object>> getCategoriesForAdmin(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Long storeId) {
        try {
            Pageable pageable = PageRequest.of(page - 1, size);
            Page<Category> categoryPage = categoryService.findCategoriesForAdmin(keyword, status, storeId, pageable);
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", categoryPage.getContent());
            result.put("total", categoryPage.getTotalElements());
            result.put("page", page);
            result.put("size", size);
            result.put("totalPages", categoryPage.getTotalPages());
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("查询分类失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取分类详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Category> getCategoryDetail(@PathVariable Long id) {
        Category category = categoryService.findById(id);
        if (category == null) {
            return ApiResponse.notFound("分类不存在");
        }
        return ApiResponse.success(category);
    }
    
    /**
     * 创建分类
     */
    @PostMapping
    public ApiResponse<Category> createCategory(@RequestBody Category category) {
        try {
            Category savedCategory = categoryService.save(category);
            return ApiResponse.success(savedCategory);
        } catch (Exception e) {
            return ApiResponse.error("创建分类失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新分类
     */
    @PutMapping("/{id}")
    public ApiResponse<Category> updateCategory(@PathVariable Long id, @RequestBody Category category) {
        try {
            Category existingCategory = categoryService.findById(id);
            if (existingCategory == null) {
                return ApiResponse.error("分类不存在");
            }
            category.setId(id);
            Category savedCategory = categoryService.save(category);
            return ApiResponse.success(savedCategory);
        } catch (Exception e) {
            return ApiResponse.error("更新分类失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除分类
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteCategory(@PathVariable Long id) {
        try {
            Category category = categoryService.findById(id);
            if (category == null) {
                return ApiResponse.error("分类不存在");
            }
            categoryService.deleteById(id);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("删除分类失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量删除分类
     */
    @DeleteMapping("/batch")
    public ApiResponse<Void> deleteCategories(@RequestBody List<Long> ids) {
        try {
            categoryService.deleteByIds(ids);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("批量删除分类失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新分类状态
     */
    @PutMapping("/{id}/status")
    public ApiResponse<Void> updateCategoryStatus(@PathVariable Long id, @RequestParam String status) {
        try {
            categoryService.updateStatus(id, status);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("更新分类状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新分类排序
     */
    @PutMapping("/{id}/sort")
    public ApiResponse<Void> updateCategorySort(@PathVariable Long id, @RequestParam Integer sortOrder) {
        try {
            categoryService.updateSortOrder(id, sortOrder);
            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("更新分类排序失败: " + e.getMessage());
        }
    }
} 